<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑任务' : '新建任务'"
    width="800px"
    :close-on-click-modal="false"
  >
    <DynamicForm
      ref="formRef"
      v-model="formData"
      :form-config="formConfig"
      :gutter="16"
      label-width="120px"
      type="submit"
      @submit="handleSubmit"
      @cancel="handleCancel"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import { createPanTask, updatePanTask } from "../../../servers";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  task: { type: Object, default: null },
  isEdit: { type: Boolean, default: false },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "save"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const formRef = ref<DynamicFormInstance>();
const formData = ref({
  task_name: "",
  main_keyword: "",
  scenario_type: "",
  task_type: "standard",
  schedule_enabled: false,
  cron_expression: "",
  description: "",
  weight: 1.0,
  timezone: "Asia/Shanghai",
});

// 场景类型选项
const scenarioOptions = [
  { label: "财务敏感信息", value: "financial" },
  { label: "人事薪酬信息", value: "hr" },
  { label: "商业合同", value: "contract" },
  { label: "技术资料", value: "tech" },
  { label: "客户信息", value: "customer" },
];

// 任务类型选项
const taskTypeOptions = [
  { label: "快速扫描 (1页)", value: "quick" },
  { label: "标准扫描 (3页)", value: "standard" },
  { label: "深度扫描 (5页)", value: "deep" },
];

// 表单配置
const formConfig = computed<FormItemConfig[]>(() => [
  {
    key: "task_name",
    name: "任务名称",
    type: "input",
    required: true,
    placeholder: "请输入任务名称",
    params: { maxLength: 100 },
    rules: [
      { required: true, message: "请输入任务名称", trigger: "blur" },
      {
        min: 1,
        max: 100,
        message: "任务名称长度应在1-100个字符之间",
        trigger: "blur",
      },
    ],
  },
  {
    key: "main_keyword",
    name: "主关键词",
    type: "input",
    required: true,
    placeholder: "请输入主关键词",
    params: { maxLength: 50 },
    rules: [
      { required: true, message: "请输入主关键词", trigger: "blur" },
      {
        min: 1,
        max: 50,
        message: "主关键词长度应在1-50个字符之间",
        trigger: "blur",
      },
    ],
  },
  {
    key: "scenario_type",
    name: "场景类型",
    type: "select",
    placeholder: "请选择场景类型（可选）",
    params: { clearable: true },
    options: scenarioOptions,
  },
  {
    key: "task_type",
    name: "任务类型",
    type: "select",
    defaultValue: "standard",
    placeholder: "请选择任务类型",
    options: taskTypeOptions,
  },
  {
    key: "schedule_enabled",
    name: "启用定时调度",
    type: "switch",
    defaultValue: false,
  },
  {
    key: "cron_expression",
    name: "Cron表达式",
    type: "input",
    placeholder: "例如: 0 2 * * * (每天凌晨2点)",
    show: (data: any) => data?.schedule_enabled === true,
    rules: [
      {
        validator: (rule: any, value: string, callback: any) => {
          if (formData.value.schedule_enabled && !value) {
            callback(new Error("启用调度时必须填写Cron表达式"));
          } else if (value && !/^(\S+\s+){4}\S+$/.test(value)) {
            callback(new Error("Cron表达式格式错误，应为5个字段"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
  },
  {
    key: "description",
    name: "任务描述",
    type: "textarea",
    placeholder: "请输入任务描述（可选）",
    params: { rows: 3, maxLength: 500 },
  },
  {
    key: "weight",
    name: "任务权重",
    type: "number",
    defaultValue: 1.0,
    params: { min: 0.1, max: 10, step: 0.1, precision: 1 },
  },
  {
    key: "timezone",
    name: "时区",
    type: "select",
    defaultValue: "Asia/Shanghai",
    options: [
      { label: "Asia/Shanghai (中国标准时间)", value: "Asia/Shanghai" },
      { label: "UTC (协调世界时)", value: "UTC" },
    ],
  },
]);

// 监听弹窗打开，初始化表单数据
watch(visible, (newVal) => {
  if (newVal) {
    if (props.isEdit && props.task) {
      // 编辑模式：填充表单
      formData.value = {
        task_name: props.task.task_name || "",
        main_keyword: props.task.main_keyword || "",
        scenario_type: props.task.scenario_type || "",
        task_type: props.task.task_type || "standard",
        schedule_enabled: props.task.schedule_enabled || false,
        cron_expression: props.task.cron_expression || "",
        description: props.task.description || "",
        weight: props.task.weight || 1.0,
        timezone: props.task.timezone || "Asia/Shanghai",
      };
    } else {
      // 新增模式：重置表单
      formData.value = {
        task_name: "",
        main_keyword: "",
        scenario_type: "",
        task_type: "standard",
        schedule_enabled: false,
        cron_expression: "",
        description: "",
        weight: 1.0,
        timezone: "Asia/Shanghai",
      };
    }
  }
});

// 提交表单
const handleSubmit = async () => {
  try {
    // 验证表单
    await formRef.value?.validate();

    // 如果启用了调度但没有填写Cron表达式，提示错误
    if (formData.value.schedule_enabled && !formData.value.cron_expression) {
      ElMessage.warning("启用调度时必须填写Cron表达式");
      return;
    }

    // 构建提交数据
    const submitData: any = {
      task_name: formData.value.task_name,
      main_keyword: formData.value.main_keyword,
      task_type: formData.value.task_type,
      schedule_enabled: formData.value.schedule_enabled,
      weight: formData.value.weight,
      timezone: formData.value.timezone,
    };

    // 可选字段
    if (formData.value.scenario_type) {
      submitData.scenario_type = formData.value.scenario_type;
    }
    if (formData.value.cron_expression) {
      submitData.cron_expression = formData.value.cron_expression;
    }
    if (formData.value.description) {
      submitData.description = formData.value.description;
    }

    if (props.isEdit && props.task?.id) {
      // 更新任务
      const result = await updatePanTask(props.task.id, submitData);

        ElMessage.success(result.message || "任务更新成功");
        emit("save");
        visible.value = false;
  
    } else {
      // 创建任务
      const result = await createPanTask(submitData);
     
        ElMessage.success(result.message || "任务创建成功");
        emit("save");
        visible.value = false;

    }
  } catch (error: any) {
    if (error !== false) {
      // false 表示验证失败，不需要显示错误
      ElMessage.error(error?.message || "操作失败");
    }
  }
};

// 取消
const handleCancel = () => {
  visible.value = false;
};
</script>

<style scoped lang="scss"></style>
